//
//  MainDetaileViewController.m
//  AIM
//
//  Created by user10 on 2017/5/16.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "MainDetaileViewController.h"
#import "NetWorkTools.h"
#import <UIImageView+WebCache.h>
#import "VideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <FSAudioStream.h>
#import "editViewController.h"
#import "chatViewController.h"
#import "RecordAudio.h"
#import "playVoiceViewController.h"
#import "EnteringViewController.h"
#import "logModel.h"
#import "DataBase.h"

#define BIG_IMG_WIDTH  [UIScreen mainScreen].bounds.size.width
#define BIG_IMG_HEIGHT [UIScreen mainScreen].bounds.size.width * 16 / 9

@interface MainDetaileViewController ()<NSStreamDelegate,editViewDelegate,UIScrollViewDelegate,AVPlayerViewControllerDelegate>
{
    
    NSInputStream *_inputStream;//对应输入流
    
    NSOutputStream *_outputStream;//对应输出流
    
}
@property (weak, nonatomic) IBOutlet UIView *VMune;
@property (weak, nonatomic) IBOutlet UIImageView *imageV;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIButton *CommentBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeL;
@property (weak, nonatomic) IBOutlet UILabel *categoryL;
@property (weak, nonatomic) IBOutlet UILabel *fromL;
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@property (weak, nonatomic) IBOutlet UILabel *detailL;
@property (weak, nonatomic) IBOutlet UITextView *detailT;

@property (strong, nonatomic)NSDictionary *resultDict;
@property (weak, nonatomic) IBOutlet UIButton *muneBtn;
@property (nonatomic, strong) AVPlayerViewController  *avPlayer;
@property (nonatomic, strong) FSAudioStream *audioStream;
//scoket 相关
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewConstraint;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *chatMsgs;//聊天消息数组

@property (nonatomic, strong)RecordAudio *recordAudio;
@property (nonatomic, strong)NSString *categoryStr;
@property (nonatomic, strong)NSMutableArray *toArr;
@property (nonatomic, strong)NSMutableArray *tagArr;
@end


@implementation MainDetaileViewController{
    UIScrollView *background;
    UIImageView *imageView;
}

//scoket聊天数组
-(NSMutableArray *)chatMsgs{
    
    if(!_chatMsgs) {
        
        _chatMsgs =[NSMutableArray array];
        
    }
    
    return _chatMsgs;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _toArr =[NSMutableArray array];
    _tagArr =[NSMutableArray array];
    //设置圆角按钮
    _closeBtn.layer.cornerRadius = 5;
    _CommentBtn.layer.cornerRadius = 5;
    _VMune.layer.cornerRadius = 5;
    
    //允许用户交互
    _imageV.userInteractionEnabled = YES;
    RecordAudio *recordAudio = [[RecordAudio alloc]init];
    _recordAudio = recordAudio;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Foreground) name:@"Foreground" object:nil];
    
    [self loadData];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Foreground" object:nil];
}
- (void)Foreground{
    
    [self loadData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _VMune.hidden = YES;
}

- (void)loadData
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:getPostDetailData>\
                                       <arg0>%@</arg0>\
                                       <arg1>%@</arg1>\
                                       </web:getPostDetailData>",COMPANY,_messageId];
            
            NetWorkTools *tools = [NetWorkTools shareTools];
            
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostDetailImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                NSRange startRange = [string rangeOfString:@"@@"];
                NSRange endRange = [string rangeOfString:@"</return>"];
                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                NSString *resultString = [string substringWithRange:range];
                
                NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                _resultDict = [getDict objectForKey:@"DATA_KEY"];
                _timeL.text = [_resultDict objectForKey:@"POSTDETAIL_POSTDATE"];
                _categoryL.text = [_resultDict objectForKey:@"POSTDETAIL_CATEGORY"];
                _fromL.text = [_resultDict objectForKey:@"POSTDETAIL_FROM"];
                _titleL.text = [_resultDict objectForKey:@"POSTDETAIL_TITLE"];
                _detailT.text = [_resultDict objectForKey:@"POSTDETAIL_MEMO"];
                [_imageV sd_setImageWithURL:[NSURL URLWithString:[_resultDict objectForKey:@"POSTDETAIL_IMG"]]placeholderImage:[UIImage imageNamed:@"icon"]];
                NSString *videoStr = [_resultDict objectForKey:@"POSTDETAIL_VIDEO"];
                NSString *voiceStr = [_resultDict objectForKey:@"POSTDETAIL_VOICE"];
                //添加点击手势
                if (videoStr.length != 0) {
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideo)];
                    
                    [_imageV addGestureRecognizer:tapGesture];
                    //AUDIO
                }else if(voiceStr.length != 0){
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAudio)];
                    [_imageV addGestureRecognizer:tapGesture];
                    _imageV.contentMode = UIViewContentModeCenter;
                    [_imageV setImage:[UIImage imageNamed:@"play_r6"]];
                }else{
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
                    [_imageV addGestureRecognizer:tapGesture];
                }
                NSString *tempStr = [_resultDict objectForKey:@"POSTDETAIL_TANTO_CD"];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//                NSString * tmp = [user objectForKey:@"TANTO_CD"];
                
                if ([tempStr isEqualToString:[user objectForKey:@"TANTO_CD"]]) {
                    _muneBtn.hidden = NO;
                }else{
                    _muneBtn.hidden = YES;
                }
            }];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
}

//播放音频
- (void)playAudio
{
    NSString *urlstr =[_resultDict objectForKey:@"POSTDETAIL_VOICE"];
    NSURL *voiceUrl = [NSURL URLWithString:urlstr];
    NSData *voiceData = [NSData dataWithContentsOfURL:voiceUrl];
//    [_recordAudio play:voiceData];
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main"bundle:nil];
    playVoiceViewController *voiceVc = [story instantiateViewControllerWithIdentifier:@"playVoiceViewController"];
    
    voiceVc.voiceData = voiceData;
//    [self.navigationController pushViewController:voiceVc animated:YES];
    [self presentViewController:voiceVc animated:YES completion:nil];
    
}
//点击图片后的方法
- (void)tapAction{
    //创建一个黑色背景
    //初始化一个用来当做背景的View。
    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    background = bgView;
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [self.view addSubview:bgView];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH, [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_imageV.image];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    } else {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_imageV.image];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake(BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    }
    
    
    
}
//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

-(void)closeView{
    
    [background removeFromSuperview];
}
- (IBAction)deleteBtn:(UIButton *)sender {
        
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:deletePostDetailData>\
                                       <arg0>%@</arg0>\
                                       <arg1>%@</arg1>\
                                       </web:deletePostDetailData>",COMPANY,_messageId];
            
            NetWorkTools *tools = [NetWorkTools shareTools];
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostDetailImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSDate *date = [NSDate date]; // 获得时间对象
                
                NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
                
                [forMatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
                
                NSString *dateStr = [forMatter stringFromDate:date];
                
                logModel *log = [[logModel alloc]init];
                if (error == NULL) {
                    log.time = dateStr;
                    log.opration = [NSString stringWithFormat:@"DELETE id%@ success",_messageId];
                    log.type = @"";
                    log.filename = @"";
                    [[DataBase sharedDataBase]addLogModel:log];
                }else{
                    log.time = dateStr;
                    log.opration = [NSString stringWithFormat:@"DELETE id%@ fail",_messageId];
                    log.type = @"";
                    log.filename = @"";
                    [[DataBase sharedDataBase]addLogModel:log];
                }
                
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
    if ([self.delegate respondsToSelector:@selector(refreash)]) {
        // 调用代理对象的刷新方法，代理对象去实现方法
        [self.delegate refreash];
    }
}

//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillDisappear:animated];
}
//关闭按钮的方法
- (IBAction)CloseBtn:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(refreash)]) {
        // 调用代理对象的刷新方法，代理对象去实现方法
        [self.delegate refreash];
    }
    [_avPlayer.player pause];
    [_audioStream pause];
    [self.navigationController popViewControllerAnimated:YES];
}
//V按钮的方法
- (IBAction)VBtn:(UIButton *)sender {
    if(_VMune.hidden == NO){
        _VMune.hidden = YES;
    }else{
        _VMune.hidden = NO;
    }
}
//edit按钮
- (IBAction)edit:(UIButton *)sender {
//    editViewController *edit = [[editViewController alloc]init];
//    edit.img = _imageV.image;
//    edit.editDelegate = self;
//    edit.messageId = _messageId;
//    [self.navigationController pushViewController:edit animated:YES];
    
    EnteringViewController *enter = [[EnteringViewController alloc]init];
    enter.messageId = _messageId;
    [self.navigationController pushViewController:enter animated:YES];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)CommentBtn:(UIButton *)sender {
    chatViewController *chatVc= [[chatViewController alloc]init];
    chatVc.messageID = _messageId;
    chatVc.timeStr = _timeL.text;
    chatVc.categoryStr = _categoryL.text;
    chatVc.fromStr = _fromL.text;
    chatVc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:chatVc animated:YES];
}
#pragma mark -- 视频播放及其代理
//播放视频
- (void)playVideo
{
    NSString *url = [_resultDict objectForKey:@"POSTDETAIL_VIDEO"];
    NSURL * videoURL = [NSURL URLWithString:url];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"error = %@",[error description]);
    }
    
    _avPlayer = [[AVPlayerViewController alloc] init];
    //    _avPlayer.player = [[AVPlayer alloc] initWithURL:videoURL];
    _avPlayer.delegate = self;
    _avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    _avPlayer.player = player;
    [self presentViewController:_avPlayer animated:YES completion:^{
        [_avPlayer.player play];
    }];
    //可以选择支持或者不支持最小化  设置NO为不支持
    //    _avPlayer.allowsPictureInPicturePlayback = NO;
    
}

- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController
{
    //表示最小化后，dismiss掉原来视图的的layer
    return YES;
}

- (void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler
{
    //恢复原来的视图 重新present
    [self presentViewController:playerViewController animated:YES completion:^{
        completionHandler(YES);
    }];
    
}


@end
